"""
统一支付API接口
支持多支付渠道：40Seas、Stripe等
"""

import frappe
from frappe.utils import get_datetime
from upsystem.upsystem.payment_manager import PaymentManager
from typing import Dict, Any, Optional
import json


@frappe.whitelist()
def create_payment(amount: float, 
                  currency: str = "USD",
                  payment_channel: str = "40ss",
                  recv_user_id: str = None,
                  metadata=None) -> Dict[str, Any]:
    """
    创建支付
    
    Args:
        amount: 支付金额
        currency: 货币类型，默认USD
        payment_channel: 支付渠道，默认40ss
        recv_user_id: 收款用户ID
        metadata: 元数据
    
    Returns:
        Dict: 支付信息
    """
    try:
        if not amount or amount <= 0:
            return {"success": False, "error": "Payment amount must be greater than 0"}
        
        if not currency:
            return {"success": False, "error": "Currency cannot be empty"}
        
        # 解析metadata
        if isinstance(metadata, str):
            try:
                metadata = json.loads(metadata) if metadata else {}
            except:
                metadata = {}
        elif metadata is None:
            metadata = {}
        
        # 创建支付管理器
        payment_manager = PaymentManager()
        
        # 创建支付
        result = payment_manager.create_payment(
            payment_channel=payment_channel,
            amount=amount,
            currency=currency,
            recv_user_id=recv_user_id,
            metadata=metadata
        )
        
        if result.get("success"):
            frappe.logger().info(f"[支付API] 创建支付成功: {result['data']['payment_id']}")
        else:
            frappe.logger().error(f"[支付API] 创建支付失败: {result.get('error')}")
        
        return result
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 创建支付异常: {str(e)}")
        return {
            "success": False,
            "error": f"Failed to create payment: {str(e)}"
        }


@frappe.whitelist()
def get_payment_status(payment_id: str) -> Dict[str, Any]:
    """
    获取支付状态
    
    Args:
        payment_id: 支付ID
    
    Returns:
        Dict: 支付状态信息
    """
    try:
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}
        
        payment_manager = PaymentManager()
        result = payment_manager.get_payment_status(payment_id)
        
        return result
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 获取支付状态异常: {str(e)}")
        return {
            "success": False,
            "error": f"Failed to get payment status: {str(e)}"
        }


@frappe.whitelist()
def get_payment_list(filters=None, 
                    limit: int = 20, 
                    offset: int = 0,
                    company: Optional[str] = None) -> Dict[str, Any]:
    """
    获取支付记录列表
    
    Args:
        filters: 过滤条件
        limit: 每页数量
        offset: 偏移量
    
    Returns:
        Dict: 支付记录列表
    """
    try:
        # 处理filters参数
        if isinstance(filters, str):
            try:
                filters = json.loads(filters) if filters else {}
            except:
                filters = {}
        elif filters is None:
            filters = {}
        
        # 构建查询条件（强制公司隔离）
        where_conditions = []
        # company：从显式参数 > filters.company > 用户默认公司
        company_val = company or (filters.get('company') if isinstance(filters, dict) else None) or frappe.defaults.get_user_default("Company")
        if not company_val:
            return {"success": False, "error": "company is required for listing payments"}
        where_conditions.append(f"company = '{company_val}'")
        if filters:
            if filters.get('payment_channel'):
                where_conditions.append(f"payment_channel = '{filters['payment_channel']}'")
            if filters.get('status'):
                where_conditions.append(f"status = '{filters['status']}'")
            if filters.get('recv_user_id'):
                where_conditions.append(f"recv_user_id = '{filters['recv_user_id']}'")
            if filters.get('date_from'):
                where_conditions.append(f"creation >= '{filters['date_from']}'")
            if filters.get('date_to'):
                where_conditions.append(f"creation <= '{filters['date_to']}'")
        
        where_clause = " AND ".join(where_conditions) if where_conditions else "1=1"
        
        # 查询数据
        payments = frappe.db.sql(f"""
            SELECT 
                name, checkout_id, payment_channel, currency,
                amount, payment_url, status, recv_user_id, notification_status, 
                notification_times, payment_token, payment_data,
                creation, modified
            FROM `taboms_payment`
            WHERE {where_clause}
            ORDER BY creation DESC
            LIMIT {limit} OFFSET {offset}
        """, as_dict=True)
        
        # 获取总数
        total = frappe.db.sql(f"""
            SELECT COUNT(*) as total
            FROM `taboms_payment`
            WHERE {where_clause}
        """, as_dict=True)[0].total
        
        return {
            "success": True,
            "data": {
                "payments": payments,
                "total": total,
                "limit": limit,
                "offset": offset
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 获取支付列表失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def get_payment_detail(payment_id: str) -> Dict[str, Any]:
    """
    获取支付记录详情
    
    Args:
        payment_id: 支付记录ID
    
    Returns:
        Dict: 支付记录详情
    """
    try:
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}
        
        doc = frappe.get_doc("oms_payment", payment_id)
        
        return {
            "success": True,
            "data": {
                "name": doc.name,
                "checkout_id": doc.checkout_id,
                "payment_channel": doc.payment_channel,
                "currency": doc.currency,
                "amount": doc.amount,
                "payment_url": doc.payment_url,
                "status": doc.status,
                "recv_user_id": doc.recv_user_id,
                "notification_status": doc.notification_status,
                "notification_times": doc.notification_times,
                "payment_token": doc.payment_token,
                "payment_data": doc.payment_data,
                "creation": doc.creation,
                "modified": doc.modified
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 获取支付详情失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def update_payment_status(payment_id: str, 
                         status: str, 
                         notification_status: str = None) -> Dict[str, Any]:
    """
    更新支付状态
    
    Args:
        payment_id: 支付记录ID
        status: 支付状态
        notification_status: 通知状态
    
    Returns:
        Dict: 更新结果
    """
    try:
        if not payment_id or not status:
            return {"success": False, "error": "Payment ID and status cannot be empty"}
        
        doc = frappe.get_doc("oms_payment", payment_id)
        doc.status = status
        
        if notification_status:
            doc.notification_status = notification_status
        
        doc.save(ignore_permissions=True)
        
        frappe.logger().info(f"[支付API] 更新支付状态: {payment_id} -> {status}")
        
        return {
            "success": True,
            "message": "Status updated successfully"
        }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 更新支付状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def retry_payment(payment_id: str) -> Dict[str, Any]:
    """
    重试支付（重新创建支付意图）
    
    Args:
        payment_id: 支付记录ID
    
    Returns:
        Dict: 重试结果
    """
    try:
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}
        
        doc = frappe.get_doc("oms_payment", payment_id)
        
        if doc.status == "paid":
            return {
                "success": False,
                "error": "支付已完成，无需重试"
            }
        
        # 重新创建支付意图
        payment_manager = PaymentManager()
        channel = payment_manager.channels.get(doc.payment_channel)
        
        if not channel:
            return {
                "success": False,
                "error": f"支付渠道 {doc.payment_channel} 不存在"
            }
        
        intent_result = channel.create_payment_intent(doc.checkout_id)
        
        if intent_result.get('success'):
            doc.payment_token = intent_result.get('payment_token')
            doc.payment_url = intent_result.get('payment_url')
            doc.status = "pending"
            doc.notification_status = "pending"
            doc.save(ignore_permissions=True)
            
            return {
                "success": True,
                "data": {
                    "payment_token": intent_result.get('payment_token'),
                    "payment_url": intent_result.get('payment_url')
                },
                "message": "支付重试成功"
            }
        else:
            return {
                "success": False,
                "error": intent_result.get('error', '重新创建支付意图失败')
            }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 重试支付失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def get_available_channels() -> Dict[str, Any]:
    """
    获取可用的支付渠道
    
    Returns:
        Dict: 可用支付渠道列表
    """
    try:
        payment_manager = PaymentManager()
        channels = payment_manager.get_available_channels()
        
        return {
            "success": True,
            "data": channels
        }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 获取支付渠道失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist(allow_guest=True)
def webhook_handler(payment_channel: str = "40ss"):
    """
    处理支付渠道 Webhook 通知
    
    Args:
        payment_channel: 支付渠道名称
    
    Returns:
        Dict: 处理结果
    """
    try:
        payload = frappe.request.data.decode('utf-8')
        data = json.loads(payload)
        
        frappe.logger().info(f"[支付Webhook] 收到 {payment_channel} 通知: {data}")
        
        # 使用支付管理器处理 Webhook
        payment_manager = PaymentManager()
        result = payment_manager.handle_webhook(payment_channel, data)
        
        if result.get("success"):
            frappe.response["message"] = "Webhook processed successfully"
            frappe.response["http_status_code"] = 200
        else:
            frappe.response["message"] = f"Webhook processing failed: {result.get('error')}"
            frappe.response["http_status_code"] = 400
            
    except Exception as e:
        frappe.logger().error(f"[支付Webhook] 处理失败: {str(e)}")
        frappe.response["message"] = f"Error processing webhook: {str(e)}"
        frappe.response["http_status_code"] = 500


# ==================== 40Seas 专用接口（向后兼容） ====================

@frappe.whitelist()
def create_buyer_for_payment(email: str, 
                           display_name: str, 
                           country: str = "US", 
                           phone: str = None) -> Dict[str, Any]:
    """
    创建40Seas买家（向后兼容接口）
    """
    try:
        # 40Seas 要求国家为 ISO2 大写编码，这里统一转大写，避免传入 'cn' 之类被校验拒绝
        country = (country or "US").upper()
        payment_manager = PaymentManager()
        channel = payment_manager.channels.get('40ss')
        
        if not channel:
            return {
                "success": False,
                "error": "40Seas 支付渠道未配置"
            }
        
        result = channel.create_buyer(
            email=email,
            display_name=display_name,
            country=country,
            phone=phone
        )
        
        return result
        
    except Exception as e:
        frappe.logger().error(f"[40Seas API] 创建买家失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def delete_payment(payment_id: str) -> Dict[str, Any]:
    """
    删除支付记录
    
    Args:
        payment_id: 支付记录ID
    
    Returns:
        Dict: 删除结果
    """
    try:
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}
        
        # 检查支付记录是否存在
        if not frappe.db.exists("oms_payment", payment_id):
            return {"success": False, "error": "Payment record does not exist"}
        
        # 检查支付状态，已支付的记录不能删除
        doc = frappe.get_doc("oms_payment", payment_id)
        if doc.status == "paid":
            return {
                "success": False, 
                "error": "Paid records cannot be deleted"
            }
        
        # 删除记录
        frappe.delete_doc("oms_payment", payment_id, ignore_permissions=True)
        
        frappe.logger().info(f"[支付API] 删除支付记录: {payment_id}")
        
        return {
            "success": True,
            "message": "Payment record deleted successfully"
        }
        
    except Exception as e:
        frappe.logger().error(f"[支付API] 删除支付记录失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }


@frappe.whitelist()
def create_payment_intent(payment_id: str) -> Dict[str, Any]:
    """
    为现有支付记录创建40Seas支付意图（不创建新记录）
    
    Args:
        payment_id: 现有的支付记录ID
    
    Returns:
        Dict: 支付意图创建结果
    """
    try:
        # 参数验证
        if not payment_id:
            return {"success": False, "error": "Payment ID cannot be empty"}
        
        # 检查支付记录是否存在
        if not frappe.db.exists("oms_payment", payment_id):
            return {"success": False, "error": "Payment record does not exist"}
        
        payment_doc = frappe.get_doc("oms_payment", payment_id)
        
        # 检查必要字段
        if not payment_doc.amount:
            return {"success": False, "error": "Payment record missing required information (amount)"}
        
        # 创建支付管理器
        payment_manager = PaymentManager()
        channel = payment_manager.channels.get('40ss')
        
        if not channel:
            frappe.logger().error("[支付意图] 40ss payment channel not configured")
            return {"success": False, "error": "40ss payment channel not configured"}

        # 检查是否已有 checkout_id（必须是 40Seas 创建 checkout 时返回的值）
        if not payment_doc.checkout_id:
            frappe.logger().error(
                f"[支付意图] 支付记录缺少 checkout_id，请先通过支付渠道创建 checkout。payment_id={payment_id}"
            )
            return {
                "success": False,
                "error": "Payment record has no checkout_id, please create 40ss payable / checkout first",
            }

        # 创建支付意图（生成支付URL）——前提是 checkout_id 已通过支付渠道创建完成
        payment_intent_result = channel.create_payment_intent(payment_doc.checkout_id)
        
        if payment_intent_result.get('success'):
            # 更新支付记录
            payment_doc.payment_url = payment_intent_result.get('payment_url')
            payment_doc.payment_token = payment_intent_result.get('payment_token')
            payment_doc.save(ignore_permissions=True)
            
            return {
                "success": True,
                "data": {
                    "payment_id": payment_doc.name,
                    "checkout_id": payment_doc.checkout_id,
                    "payment_url": payment_intent_result.get('payment_url'),
                    "payment_token": payment_intent_result.get('payment_token'),
                    "amount": payment_doc.amount,
                    "currency": payment_doc.currency,
                },
                # 把底层40Seas返回结果一并带回，方便排查
                "intent_result": payment_intent_result,
                "message": "Payment intent created successfully",
            }
        else:
            return {
                "success": False,
                "error": f"Failed to create payment intent: {payment_intent_result.get('error')}",
                "intent_result": payment_intent_result,
            }
        
    except Exception as e:
        frappe.logger().error(
            f"[支付意图] 创建失败, payment_id={payment_id}, traceback={frappe.get_traceback()}"
        )
        return {
            "success": False,
            "error": f"Failed to create payment intent: {str(e)}"
        }


@frappe.whitelist()
def send_email_notification(payment_id: str, company: str) -> Dict[str, Any]:
    """
    发送邮件通知 - 给指定公司发送支付链接
    
    Args:
        payment_id: 支付记录ID
        company: 公司名称
    
    Returns:
        Dict: 发送结果
    """
    try:
        # 参数验证
        if not payment_id or not company:
            return {"success": False, "error": "支付ID和公司不能为空"}
        
        
        # 检查支付记录是否存在
        if not frappe.db.exists("oms_payment", payment_id):
            return {"success": False, "error": "Payment record does not exist"}
        
        payment_doc = frappe.get_doc("oms_payment", payment_id)
        
        # 检查是否有支付URL
        if not payment_doc.payment_url:
            return {"success": False, "error": "该支付记录没有支付链接"}
        
        # 构造收件人：优先使用 Receiver User 的邮箱
        recipients: list[str] = []
        primary_email = None

        # 1) Receiver User 邮箱（优先）
        recv_user_id = getattr(payment_doc, "recv_user_id", None)
        if recv_user_id:
            try:
                user_doc = frappe.get_doc("User", recv_user_id)
                if getattr(user_doc, "email", None):
                    primary_email = user_doc.email
                    recipients.append(user_doc.email)
            except Exception:
                frappe.logger().error(
                    f"[邮件通知] 获取收款用户邮箱失败, payment_id={payment_id}, "
                    f"recv_user_id={recv_user_id}, traceback={frappe.get_traceback()}"
                )

        # 构建邮件内容
        subject = f"Payment Notification - {payment_doc.name}"
        message = f"""
        Hello,
        
        You have a pending payment order that needs to be processed:
        
        Payment ID: {payment_doc.name}
        Amount: {payment_doc.amount} {payment_doc.currency}
        Status: {payment_doc.status}
        
        Please click the following link to complete the payment:
        {payment_doc.payment_url}
        
        This email is automatically sent by the Flowa OMSsystem.
        
        Thank you!
        """
        
        # 发送邮件
        frappe.sendmail(
            recipients=recipients,
            subject=subject,
            message=message,
            reference_doctype="oms_payment",
            reference_name=payment_doc.name,
        )
        
        # 更新发送次数和通知状态（使用 DocType 上的 notification_times 字段）
        current_times = getattr(payment_doc, "notification_times", 0) or 0
        payment_doc.notification_times = int(current_times) + 1
        payment_doc.notification_status = "sent"
        payment_doc.save(ignore_permissions=True)
        
        return {
            "success": True,
            "send_count": payment_doc.notification_times,
            "notification_status": payment_doc.notification_status,
            "message": "Email notification sent successfully",
        }
        
    except Exception as e:
        frappe.logger().error(f"[邮件通知] 发送失败: {str(e)}")
        return {
            "success": False,
            "error": f"发送邮件通知失败: {str(e)}"
        }


@frappe.whitelist()
def create_40ss_payable(payment_id: str) -> Dict[str, Any]:
    """
    创建40ss应付 - 为现有支付记录创建40ss checkout
    
    Args:
        payment_id: 现有的支付记录ID
    
    Returns:
        Dict: 创建结果
    """
    try:
        # 参数验证
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}
        
        
        # 检查支付记录是否存在
        if not frappe.db.exists("oms_payment", payment_id):
            # 尝试检查其他可能的DocType名称
            if frappe.db.exists("oms_payment", payment_id):
                payment_doc = frappe.get_doc("oms_payment", payment_id)
            else:
                return {"success": False, "error": "关联的支付记录不存在"}
        else:
            payment_doc = frappe.get_doc("oms_payment", payment_id)
        
        # 检查必要字段
        if not payment_doc.amount:
            frappe.logger().error(
                f"[40ss应付] 支付记录缺少金额信息，payment_id={payment_id}"
            )
            return {"success": False, "error": "支付记录缺少必要信息（金额）"}
        
        # 直接创建checkout，覆盖现有值
        
        # 创建支付管理器
        payment_manager = PaymentManager()
        channel = payment_manager.channels.get('40ss')
        
        if not channel:
            frappe.logger().error("[40ss应付] 40ss支付渠道未配置")
            return {"success": False, "error": "40ss支付渠道未配置"}
        
        # 1. 先创建买家：邮箱必须存在，用于后续发送付款链接
        buyer_email = None
        buyer_name = None
        buyer_country = "US"
        buyer_phone = None
        company_doc = None

        # 1.1 从 Company 取基础信息（名称 / 国家 / 邮箱）
        try:
            if getattr(payment_doc, "company", None):
                company_doc = frappe.get_doc("Company", payment_doc.company)
                # Company.country 通常是国家名称，这里转换为 ISO2 国家编码（40Seas 要求）
                country_name = getattr(company_doc, "country", None)
                if country_name:
                    try:
                        iso_code = frappe.db.get_value("Country", country_name, "code")
                        buyer_country = iso_code or buyer_country
                    except Exception:
                        buyer_country = country_name or buyer_country
                # 公司名称作为兜底名称
                buyer_name = getattr(company_doc, "company_name", None) or company_doc.name
        except Exception:
            frappe.logger().error(
                f"[40ss应付] 获取 Company 信息失败，将使用默认国家。payment_id={payment_id}, "
                f"traceback={frappe.get_traceback()}"
            )

        # 1.2 优先使用收款用户（recv_user_id）的邮箱
        try:
            recv_user_id = getattr(payment_doc, "recv_user_id", None)
            if recv_user_id:
                user_doc = frappe.get_doc("User", recv_user_id)
                if getattr(user_doc, "email", None):
                    buyer_email = user_doc.email
                # 如果还没有名称，则用用户姓名做买家名称
                if not buyer_name:
                    buyer_name = getattr(user_doc, "full_name", None) or getattr(
                        user_doc, "first_name", None
                    ) or user_doc.name
                # 如果有电话信息，则一并带给 40Seas（可选）
                buyer_phone = getattr(user_doc, "phone", None) or getattr(
                    user_doc, "mobile_no", None
                ) or buyer_phone
        except Exception:
            frappe.logger().error(
                f"[40ss应付] 获取收款用户信息失败，将退回使用公司或默认邮箱。payment_id={payment_id}, "
                f"traceback={frappe.get_traceback()}"
            )

        # 1.3 仍然没有邮箱则直接报错，提示配置（公司邮箱后续不再维护，不做兜底）
        if not buyer_email:
            frappe.logger().error(
                f"[40ss应付] 收款邮箱缺失，请在收款用户或公司上配置 Email。payment_id={payment_id}"
            )
            return {
                "success": False,
                "error": "收款邮箱缺失，请在收款用户或公司上配置 Email",
            }

        if not buyer_name:
            buyer_name = f"Buyer {payment_id}"

        # 40Seas 对 address.country 做严格枚举校验，这里统一转成 ISO2 大写
        if buyer_country:
            buyer_country = buyer_country.upper()
        else:
            buyer_country = "US"
        buyer_result = channel.create_buyer(
            email=buyer_email,
            display_name=buyer_name,
            country=buyer_country,
            phone=buyer_phone,
        )
        
        if not buyer_result.get('success'):
            frappe.logger().error(
                f"[40ss应付] 创建买家失败, payment_id={payment_id}, error={buyer_result.get('error')}"
            )
            return {"success": False, "error": f"创建买家失败: {buyer_result.get('error')}"}
        
        buyer_id = buyer_result.get('buyer_id')
        # 2. 创建checkout
        checkout_result = channel.create_checkout(
            buyer_id=buyer_id,
            amount=payment_doc.amount,
            currency=payment_doc.currency or "USD",
            metadata={
                "payment_id": payment_id,
                "buyer_id": buyer_id,
                "type": "payable"
            }
        )
        
        if not checkout_result.get('success'):
            frappe.logger().error(
                f"[40ss应付] 创建checkout失败, payment_id={payment_id}, error={checkout_result.get('error')}"
            )
            return {"success": False, "error": f"创建checkout失败: {checkout_result.get('error')}"}
        
        checkout_id = checkout_result.get('checkout_id')
        payment_token = checkout_result.get('payment_token')
        payment_url = checkout_result.get('payment_url')
        # 3. 创建支付意图（生成支付URL）
        payment_intent_result = channel.create_payment_intent(checkout_id)
        
        if payment_intent_result.get('success'):
            payment_url = payment_intent_result.get('payment_url')
            payment_token = payment_intent_result.get('payment_token')
        else:
            # 即使支付意图创建失败，也继续保存checkout信息
            frappe.logger().error(
                f"[40ss应付] 创建支付意图失败, payment_id={payment_id}, checkout_id={checkout_id}, "
                f"error={payment_intent_result.get('error')}"
            )
        
        # 4. 更新支付记录
        payment_doc.checkout_id = checkout_id
        payment_doc.payment_token = payment_token
        payment_doc.payment_url = payment_url
        payment_doc.payment_channel = "40ss"
        payment_doc.status = "pending"
        payment_doc.notification_status = "pending"
        payment_doc.save(ignore_permissions=True)

        return {
            "success": True,
            "checkout_id": checkout_id,
            "payment_token": payment_token,
            "payment_url": payment_url,
            "message": "40ss应付创建成功"
        }
        
    except Exception as e:
        frappe.logger().error(
            f"[40ss应付] 创建失败, payment_id={payment_id}, traceback={frappe.get_traceback()}"
        )
        return {
            "success": False,
            "error": f"创建40ss应付失败: {str(e)}"
        }


@frappe.whitelist()
def start_40ss_payment(payment_id: str) -> Dict[str, Any]:
    """
    在 Desk 中发起 40ss 支付：
    - 如果已有 checkout_id，则只创建支付意图；
    - 如果没有 checkout_id，则先创建 40ss 应付，再返回支付链接。
    """
    try:
        if not payment_id:
            return {"success": False, "error": "支付ID不能为空"}

        if not frappe.db.exists("oms_payment", payment_id):
            return {"success": False, "error": "Payment record does not exist"}

        payment_doc = frappe.get_doc("oms_payment", payment_id)

        if payment_doc.status == "paid":
            return {"success": False, "error": "支付已完成，无需再次发起"}

        if payment_doc.payment_channel and payment_doc.payment_channel != "40ss":
            return {
                "success": False,
                "error": f"当前支付渠道不是 40ss，而是 {payment_doc.payment_channel}",
            }

        if not payment_doc.amount:
            return {"success": False, "error": "支付记录缺少必要信息（金额）"}

        # 优先复用已有 checkout
        if payment_doc.checkout_id:
            frappe.logger().error(
                f"[40ss支付] start_40ss_payment 使用已有 checkout_id, "
                f"payment_id={payment_id}, checkout_id={payment_doc.checkout_id}"
            )
            intent_result = create_payment_intent(payment_id)
            if not intent_result.get("success"):
                return intent_result
            data = intent_result.get("data") or {}
            return {
                "success": True,
                "payment_url": data.get("payment_url"),
                "payment_token": data.get("payment_token"),
                "data": data,
                "message": intent_result.get("message") or "Payment intent created",
            }

        # 否则先创建 40ss 应付
        frappe.logger().error(
            f"[40ss支付] start_40ss_payment 无 checkout_id，调用 create_40ss_payable, "
            f"payment_id={payment_id}"
        )
        payable_result = create_40ss_payable(payment_id)
        return payable_result

    except Exception as e:
        frappe.logger().error(
            f"[40ss支付] start_40ss_payment 异常, payment_id={payment_id}, traceback={frappe.get_traceback()}"
        )
        return {
            "success": False,
            "error": f"start_40ss_payment failed: {str(e)}",
        }